{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 204 Agent Prompt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在agent中，我们是如何写提示词的，带着这个问题我们来看一下别人的提示词"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "#设置代理\n",
    "import os\n",
    "\n",
    "os.environ['http_proxy'] = 'http://127.0.0.1:10809'\n",
    "os.environ['https_proxy'] = 'http://127.0.0.1:10809'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'input_variables=[\\'agent_scratchpad\\', \\'input\\', \\'tools\\'] partial_variables={\\'chat_history\\': \\'\\'} messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=[\\'agent_scratchpad\\', \\'chat_history\\', \\'input\\', \\'tools\\'], template=\"You are a helpful assistant. Help the user answer any questions.\\n\\nYou have access to the following tools:\\n\\n{tools}\\n\\nIn order to use a tool, you can use <tool></tool> and <tool_input></tool_input> tags. You will then get back a response in the form <observation></observation>\\nFor example, if you have a tool called \\'search\\' that could run a google search, in order to search for the weather in SF you would respond:\\n\\n<tool>search</tool><tool_input>weather in SF</tool_input>\\n<observation>64 degrees</observation>\\n\\nWhen you are done, respond with a final answer between <final_answer></final_answer>. For example:\\n\\n<final_answer>The weather in SF is 64 degrees</final_answer>\\n\\nBegin!\\n\\nPrevious Conversation:\\n{chat_history}\\n\\nQuestion: {input}\\n{agent_scratchpad}\"))]'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt = hub.pull(\"hwchase17/xml-agent-convo\")\n",
    "prompt = str(prompt).replace(\"\\\\n\", \"\\n\").replace(\"\\\\t\", \"\\t\")\n",
    "with open('promptstore/hwchase17/xml-agent-convo.txt', 'w') as file:\n",
    "    file.write(prompt)\n",
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'input_variables=[\\'agent_scratchpad\\', \\'chat_history\\', \\'input\\', \\'tool_names\\', \\'tools\\'] input_types={\\'chat_history\\': typing.List[typing.Union[langchain_core.messages.ai.AIMessage, langchain_core.messages.human.HumanMessage, langchain_core.messages.chat.ChatMessage, langchain_core.messages.system.SystemMessage, langchain_core.messages.function.FunctionMessage, langchain_core.messages.tool.ToolMessage]], \\'agent_scratchpad\\': typing.List[typing.Union[langchain_core.messages.ai.AIMessage, langchain_core.messages.human.HumanMessage, langchain_core.messages.chat.ChatMessage, langchain_core.messages.system.SystemMessage, langchain_core.messages.function.FunctionMessage, langchain_core.messages.tool.ToolMessage]]} messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[], template=\\'Assistant is a large language model trained by OpenAI.\\n\\nAssistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\\n\\nAssistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.\\n\\nOverall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.\\')), MessagesPlaceholder(variable_name=\\'chat_history\\'), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=[\\'input\\', \\'tool_names\\', \\'tools\\'], template=\\'TOOLS\\n------\\nAssistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:\\n\\n{tools}\\n\\nRESPONSE FORMAT INSTRUCTIONS\\n----------------------------\\n\\nWhen responding to me, please output a response in one of two formats:\\n\\n**Option 1:**\\nUse this if you want the human to use a tool.\\nMarkdown code snippet formatted in the following schema:\\n\\n```json\\n{{\\n    \"action\": string, \\\\\\\\ The action to take. Must be one of {tool_names}\\n    \"action_input\": string \\\\\\\\ The input to the action\\n}}\\n```\\n\\n**Option #2:**\\nUse this if you want to respond directly to the human. Markdown code snippet formatted in the following schema:\\n\\n```json\\n{{\\n    \"action\": \"Final Answer\",\\n    \"action_input\": string \\\\\\\\ You should put what you want to return to use here\\n}}\\n```\\n\\nUSER\\\\\\'S INPUT\\n--------------------\\nHere is the user\\\\\\'s input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):\\n\\n{input}\\')), MessagesPlaceholder(variable_name=\\'agent_scratchpad\\')]'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt = hub.pull(\"hwchase17/react-chat-json\")\n",
    "prompt = str(prompt).replace(\"\\\\n\", \"\\n\").replace(\"\\\\t\", \"\\t\")\n",
    "with open('promptstore/hwchase17/react-chat-json.txt', 'w') as file:\n",
    "    file.write(prompt)\n",
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'input_variables=[\\'agent_scratchpad\\', \\'chat_history\\', \\'input\\', \\'tool_names\\', \\'tools\\'] input_types={\\'chat_history\\': typing.List[typing.Union[langchain_core.messages.ai.AIMessage, langchain_core.messages.human.HumanMessage, langchain_core.messages.chat.ChatMessage, langchain_core.messages.system.SystemMessage, langchain_core.messages.function.FunctionMessage, langchain_core.messages.tool.ToolMessage]]} messages=[SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[\\'tool_names\\', \\'tools\\'], template=\\'Respond to the human as helpfully and accurately as possible. You have access to the following tools:\\n\\n{tools}\\n\\nUse a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).\\n\\nValid \"action\" values: \"Final Answer\" or {tool_names}\\n\\nProvide only ONE action per $JSON_BLOB, as shown:\\n\\n```\\n{{\\n  \"action\": $TOOL_NAME,\\n  \"action_input\": $INPUT\\n}}\\n```\\n\\nFollow this format:\\n\\nQuestion: input question to answer\\nThought: consider previous and subsequent steps\\nAction:\\n```\\n$JSON_BLOB\\n```\\nObservation: action result\\n... (repeat Thought/Action/Observation N times)\\nThought: I know what to respond\\nAction:\\n```\\n{{\\n  \"action\": \"Final Answer\",\\n  \"action_input\": \"Final response to human\"\\n}}\\n\\nBegin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation\\')), MessagesPlaceholder(variable_name=\\'chat_history\\'), HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=[\\'agent_scratchpad\\', \\'input\\'], template=\\'{input}\\n\\n{agent_scratchpad}\\n (reminder to respond in a JSON blob no matter what)\\'))]'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt = hub.pull(\"hwchase17/structured-chat-agent\")\n",
    "prompt = str(prompt).replace(\"\\\\n\", \"\\n\").replace(\"\\\\t\", \"\\t\")\n",
    "with open('promptstore/hwchase17/structured-chat-agent.txt', 'w') as file:\n",
    "    file.write(prompt)\n",
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"input_variables=['agent_scratchpad', 'input', 'tool_names', 'tools'] template='Answer the following questions as best you can. You have access to the following tools:\\n\\n{tools}\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [{tool_names}]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: {input}\\nThought:{agent_scratchpad}'\""
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt = hub.pull(\"hwchase17/react\")\n",
    "prompt = str(prompt).replace(\"\\\\n\", \"\\n\").replace(\"\\\\t\", \"\\t\")\n",
    "with open('promptstore/hwchase17/react.txt', 'w') as file:\n",
    "    file.write(prompt)\n",
    "prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"input_variables=['agent_scratchpad', 'input'] template='Question: Who lived longer, Muhammad Ali or Alan Turing?\\nAre follow up questions needed here: Yes.\\nFollow up: How old was Muhammad Ali when he died?\\nIntermediate answer: Muhammad Ali was 74 years old when he died.\\nFollow up: How old was Alan Turing when he died?\\nIntermediate answer: Alan Turing was 41 years old when he died.\\nSo the final answer is: Muhammad Ali\\n\\nQuestion: When was the founder of craigslist born?\\nAre follow up questions needed here: Yes.\\nFollow up: Who was the founder of craigslist?\\nIntermediate answer: Craigslist was founded by Craig Newmark.\\nFollow up: When was Craig Newmark born?\\nIntermediate answer: Craig Newmark was born on December 6, 1952.\\nSo the final answer is: December 6, 1952\\n\\nQuestion: Who was the maternal grandfather of George Washington?\\nAre follow up questions needed here: Yes.\\nFollow up: Who was the mother of George Washington?\\nIntermediate answer: The mother of George Washington was Mary Ball Washington.\\nFollow up: Who was the father of Mary Ball Washington?\\nIntermediate answer: The father of Mary Ball Washington was Joseph Ball.\\nSo the final answer is: Joseph Ball\\n\\nQuestion: Are both the directors of Jaws and Casino Royale from the same country?\\nAre follow up questions needed here: Yes.\\nFollow up: Who is the director of Jaws?\\nIntermediate answer: The director of Jaws is Steven Spielberg.\\nFollow up: Where is Steven Spielberg from?\\nIntermediate answer: The United States.\\nFollow up: Who is the director of Casino Royale?\\nIntermediate answer: The director of Casino Royale is Martin Campbell.\\nFollow up: Where is Martin Campbell from?\\nIntermediate answer: New Zealand.\\nSo the final answer is: No\\n\\nQuestion: {input}\\nAre followup questions needed here:{agent_scratchpad}'\""
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt = hub.pull(\"hwchase17/self-ask-with-search\")\n",
    "prompt = str(prompt).replace(\"\\\\n\", \"\\n\").replace(\"\\\\t\", \"\\t\")\n",
    "with open('promptstore/hwchase17/self-ask-with-search.txt', 'w') as file:\n",
    "    file.write(prompt)\n",
    "prompt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# XML Agent\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: langchain in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (0.1.0)\n",
      "Requirement already satisfied: PyYAML>=5.3 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (6.0.1)\n",
      "Requirement already satisfied: SQLAlchemy<3,>=1.4 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (2.0.23)\n",
      "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (3.9.1)\n",
      "Requirement already satisfied: async-timeout<5.0.0,>=4.0.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (4.0.3)\n",
      "Requirement already satisfied: dataclasses-json<0.7,>=0.5.7 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (0.6.3)\n",
      "Requirement already satisfied: jsonpatch<2.0,>=1.33 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (1.33)\n",
      "Requirement already satisfied: langchain-community<0.1,>=0.0.9 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (0.0.10)\n",
      "Requirement already satisfied: langchain-core<0.2,>=0.1.7 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (0.1.8)\n",
      "Requirement already satisfied: langsmith<0.1.0,>=0.0.77 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (0.0.77)\n",
      "Requirement already satisfied: numpy<2,>=1 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (1.26.2)\n",
      "Requirement already satisfied: pydantic<3,>=1 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (2.5.2)\n",
      "Requirement already satisfied: requests<3,>=2 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (2.31.0)\n",
      "Requirement already satisfied: tenacity<9.0.0,>=8.1.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain) (8.2.3)\n",
      "Requirement already satisfied: attrs>=17.3.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (23.1.0)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (6.0.4)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.9.4)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.4.1)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.3->langchain) (1.3.1)\n",
      "Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from dataclasses-json<0.7,>=0.5.7->langchain) (3.20.1)\n",
      "Requirement already satisfied: typing-inspect<1,>=0.4.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from dataclasses-json<0.7,>=0.5.7->langchain) (0.9.0)\n",
      "Requirement already satisfied: jsonpointer>=1.9 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from jsonpatch<2.0,>=1.33->langchain) (2.4)\n",
      "Requirement already satisfied: anyio<5,>=3 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain-core<0.2,>=0.1.7->langchain) (3.7.1)\n",
      "Requirement already satisfied: packaging<24.0,>=23.2 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from langchain-core<0.2,>=0.1.7->langchain) (23.2)\n",
      "Requirement already satisfied: annotated-types>=0.4.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from pydantic<3,>=1->langchain) (0.6.0)\n",
      "Requirement already satisfied: pydantic-core==2.14.5 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from pydantic<3,>=1->langchain) (2.14.5)\n",
      "Requirement already satisfied: typing-extensions>=4.6.1 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from pydantic<3,>=1->langchain) (4.9.0)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from requests<3,>=2->langchain) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from requests<3,>=2->langchain) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from requests<3,>=2->langchain) (2.1.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from requests<3,>=2->langchain) (2023.11.17)\n",
      "Requirement already satisfied: greenlet!=0.4.17 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from SQLAlchemy<3,>=1.4->langchain) (3.0.3)\n",
      "Requirement already satisfied: sniffio>=1.1 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from anyio<5,>=3->langchain-core<0.2,>=0.1.7->langchain) (1.3.0)\n",
      "Requirement already satisfied: exceptiongroup in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from anyio<5,>=3->langchain-core<0.2,>=0.1.7->langchain) (1.2.0)\n",
      "Requirement already satisfied: mypy-extensions>=0.3.0 in c:\\users\\administrator\\desktop\\codeproject\\langchainstudy\\.venv\\lib\\site-packages (from typing-inspect<1,>=0.4.0->dataclasses-json<0.7,>=0.5.7->langchain) (1.0.0)\n"
     ]
    }
   ],
   "source": [
    "! pip install --upgrade langchain\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "#需要注册账户获取api，免费的 https://docs.tavily.com/docs/tavily-api/langchain\n",
    "os.environ[\"TAVILY_API_KEY\"] = \"tvly-fxxxxxxxxxGxxxxxxxxxk4dZS24\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor,create_xml_agent\n",
    "from langchain_community.chat_models import ChatOpenAI\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "prompt = hub.pull(\"hwchase17/xml-agent-convo\")\n",
    "llm = ChatOpenAI()\n",
    "agent = create_xml_agent(llm, tools, prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "RunnableAssign(mapper={\n",
       "  agent_scratchpad: RunnableLambda(lambda x: format_xml(x['intermediate_steps']))\n",
       "})\n",
       "| ChatPromptTemplate(input_variables=['agent_scratchpad', 'input'], partial_variables={'chat_history': '', 'tools': 'tavily_search_results_json: A search engine optimized for comprehensive, accurate, and trusted results. Useful for when you need to answer questions about current events. Input should be a search query.'}, messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['agent_scratchpad', 'chat_history', 'input', 'tools'], template=\"You are a helpful assistant. Help the user answer any questions.\\n\\nYou have access to the following tools:\\n\\n{tools}\\n\\nIn order to use a tool, you can use <tool></tool> and <tool_input></tool_input> tags. You will then get back a response in the form <observation></observation>\\nFor example, if you have a tool called 'search' that could run a google search, in order to search for the weather in SF you would respond:\\n\\n<tool>search</tool><tool_input>weather in SF</tool_input>\\n<observation>64 degrees</observation>\\n\\nWhen you are done, respond with a final answer between <final_answer></final_answer>. For example:\\n\\n<final_answer>The weather in SF is 64 degrees</final_answer>\\n\\nBegin!\\n\\nPrevious Conversation:\\n{chat_history}\\n\\nQuestion: {input}\\n{agent_scratchpad}\"))])\n",
       "| RunnableBinding(bound=ChatOpenAI(client=<openai.resources.chat.completions.Completions object at 0x000001CF0568F370>, async_client=<openai.resources.chat.completions.AsyncCompletions object at 0x000001CF056C2C50>, openai_api_key='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', openai_proxy=''), kwargs={'stop': ['</tool_input>']})\n",
       "| XMLAgentOutputParser()"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Json chat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_json_chat_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/react-chat-json\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = ChatOpenAI()\n",
    "# Construct the JSON agent\n",
    "agent = create_json_chat_agent(llm, tools, prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(\n",
    "    agent=agent, tools=tools, verbose=True, handle_parsing_errors=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m{\n",
      "    \"action\": \"tavily_search_results_json\",\n",
      "    \"action_input\": \"LangChain\"\n",
      "}\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://blog.langchain.dev/langchain-v0-1-0/', 'content': \"LangChain 0.2  LangChain v0.1.0  LangChain has been around for a little over a year and has changed a lot as it’s grown to become the default framework  However, starting today with the release of langchain 0.1.0, all future releases will follow a new versioning standard.10 min read Jan 8, 2024 Today we're excited to announce the release of langchain 0.1.0, our first stable version. It is fully backwards compatible, comes in both Python and JavaScript, and comes with improved focus through both functionality and documentation.\"}]\u001b[0m\u001b[32;1m\u001b[1;3m{\n",
      "    \"action\": \"Final Answer\",\n",
      "    \"action_input\": \"LangChain is a framework that has been around for over a year and has undergone changes as it has grown. The latest stable version is langchain 0.1.0, which is fully backwards compatible and available in both Python and JavaScript. It comes with improved focus through both functionality and documentation. You can find more information about LangChain [here](https://blog.langchain.dev/langchain-v0-1-0/).\"\n",
      "}\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is a framework that has been around for over a year and has undergone changes as it has grown. The latest stable version is langchain 0.1.0, which is fully backwards compatible and available in both Python and JavaScript. It comes with improved focus through both functionality and documentation. You can find more information about LangChain [here](https://blog.langchain.dev/langchain-v0-1-0/).'}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Structured chat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_structured_chat_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/structured-chat-agent\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-1106\")\n",
    "\n",
    "# Construct the JSON agent\n",
    "agent = create_structured_chat_agent(llm, tools, prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(\n",
    "    agent=agent, tools=tools, verbose=True, handle_parsing_errors=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mAction:\n",
      "```\n",
      "{\n",
      "  \"action\": \"tavily_search_results_json\",\n",
      "  \"action_input\": {\"query\": \"LangChain\"}\n",
      "}\n",
      "```\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://blog.langchain.dev/langchain-v0-1-0/', 'content': \"LangChain 0.2  LangChain v0.1.0  LangChain has been around for a little over a year and has changed a lot as it’s grown to become the default framework  However, starting today with the release of langchain 0.1.0, all future releases will follow a new versioning standard.LangChain v0.1.0. 10 min read Jan 8, 2024. Today we're excited to announce the release of langchain 0.1.0, our first stable version. It is fully backwards compatible, comes in both Python and JavaScript, and comes with improved focus through both functionality and documentation. A stable version of LangChain helps us earn developer trust and ...\"}]\u001b[0m\u001b[32;1m\u001b[1;3mCould not parse LLM output: LangChain is a framework that has been around for a little over a year and has undergone significant changes as it has grown to become the default framework. The latest release is LangChain v0.1.0, which is fully backwards compatible, available in both Python and JavaScript, and comes with improved functionality and documentation. This stable version aims to earn developer trust. For more detailed information, you can visit the following link: [LangChain v0.1.0 Release](https://blog.langchain.dev/langchain-v0-1-0/).\u001b[0mInvalid or incomplete response\u001b[32;1m\u001b[1;3mApologies for the incomplete response. LangChain is a framework that has been around for a little over a year and has undergone significant changes as it has grown to become the default framework. The latest release is LangChain v0.1.0, which is fully backwards compatible, available in both Python and JavaScript, and comes with improved functionality and documentation. This stable version aims to earn developer trust. For more detailed information, you can visit the following link: [LangChain v0.1.0 Release](https://blog.langchain.dev/langchain-v0-1-0/).\n",
      "\n",
      "Action:\n",
      "```\n",
      "{\n",
      "  \"action\": \"Final Answer\",\n",
      "  \"action_input\": \"LangChain is a framework that has been around for a little over a year and has undergone significant changes as it has grown to become the default framework. The latest release is LangChain v0.1.0, which is fully backwards compatible, available in both Python and JavaScript, and comes with improved functionality and documentation. This stable version aims to earn developer trust. For more detailed information, you can visit the following link: [LangChain v0.1.0 Release](https://blog.langchain.dev/langchain-v0-1-0/).\"\n",
      "}\n",
      "```\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is a framework that has been around for a little over a year and has undergone significant changes as it has grown to become the default framework. The latest release is LangChain v0.1.0, which is fully backwards compatible, available in both Python and JavaScript, and comes with improved functionality and documentation. This stable version aims to earn developer trust. For more detailed information, you can visit the following link: [LangChain v0.1.0 Release](https://blog.langchain.dev/langchain-v0-1-0/).'}"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## ReAct"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install langchain_openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_react_agent\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_openai import OpenAI\n",
    "tools = [TavilySearchResults(max_results=1)]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/react\")\n",
    "# Choose the LLM to use\n",
    "llm = OpenAI()\n",
    "# Construct the ReAct agent\n",
    "agent = create_react_agent(llm, tools, prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m I'm not sure what LangChain is.\n",
      "Action: tavily_search_results_json\n",
      "Action Input: LangChain\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://blog.langchain.dev/langchain-v0-1-0/', 'content': \"LangChain 0.2  LangChain v0.1.0  LangChain has been around for a little over a year and has changed a lot as it’s grown to become the default framework  However, starting today with the release of langchain 0.1.0, all future releases will follow a new versioning standard.10 min read Jan 8, 2024 Today we're excited to announce the release of langchain 0.1.0, our first stable version. It is fully backwards compatible, comes in both Python and JavaScript, and comes with improved focus through both functionality and documentation.\"}]\u001b[0m\u001b[32;1m\u001b[1;3mAfter reading the search results, it seems like LangChain is a programming framework that has been around for a year and recently released a new stable version.\n",
      "Action: tavily_search_results_json\n",
      "Action Input: LangChain framework\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://slashdev.io/blog/the-ultimate-guide-to-langchain-in-2024', 'content': 'LangChain represents the cutting edge in language model technology, heralding a new era of artificial intelligence (AI)  LangChain is built on a foundation of complex algorithms and machine learning models that form its core architecture,  LangChain’s transformative role is evident in several key areas that define the next generation of AI communication.  LangChain a highly versatile tool for building AI solutions that can cater to a broad spectrum of conversational needs.The Ultimate Guide To LangChain In 2024 LangChain represents the cutting edge in language model technology, heralding a new era of artificial intelligence (AI) with remarkable conversational abil'}]\u001b[0m\u001b[32;1m\u001b[1;3m After reading this article, it seems like LangChain is a cutting-edge programming framework that uses advanced language models and AI technology for communication.\n",
      "Final Answer: LangChain is a programming framework that utilizes advanced language models and AI technology for communication and was recently released in a stable version 0.1.0.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'what is LangChain?',\n",
       " 'output': 'LangChain is a programming framework that utilizes advanced language models and AI technology for communication and was recently released in a stable version 0.1.0.'}"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"what is LangChain?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Self-ask with search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install fireworks-ai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "# https://app.fireworks.ai/ 也是免费注册即可获得api\n",
    "os.environ[\"FIREWORKS_API_KEY\"] = \"ZvGxxxxxxxxxxxxxxxxxcB8yzbu\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_self_ask_with_search_agent\n",
    "from langchain_community.llms import Fireworks\n",
    "from langchain_community.tools.tavily_search import TavilyAnswer\n",
    "tools = [TavilyAnswer(max_results=1, name=\"Intermediate Answer\")]\n",
    "# Get the prompt to use - you can modify this!\n",
    "prompt = hub.pull(\"hwchase17/self-ask-with-search\")\n",
    "# Choose the LLM that will drive the agent\n",
    "llm = Fireworks()\n",
    "# Construct the Self Ask With Search Agent\n",
    "agent = create_self_ask_with_search_agent(llm, tools, prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an agent executor by passing in the agent and tools\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m Yes.\n",
      "Follow up: Who is the reigning men's U.S. Open champion?\u001b[0m\u001b[36;1m\u001b[1;3mRafael Nadal is the reigning men's U.S. Open champion.\u001b[0m\u001b[32;1m\u001b[1;3mFollow up: Where is Rafael Nadal from?\u001b[0m\u001b[36;1m\u001b[1;3mRafael Nadal is from Manacor, Mallorca, Spain.\u001b[0m\u001b[32;1m\u001b[1;3m\n",
      "So the final answer is: Spain\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"What is the hometown of the reigning men's U.S. Open champion?\",\n",
       " 'output': 'Spain'}"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 美国男子网球公开赛卫冕冠军的家乡是哪里？\n",
    "agent_executor.invoke(\n",
    "    {\"input\": \"What is the hometown of the reigning men's U.S. Open champion?\"}\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
